package com.library.dao.impl;

import com.library.dao.NoticeDao;
import com.library.entity.Notice;
import com.library.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NoticeDaoImpl implements NoticeDao {
    @Override
    public List<Notice> getAllNotices() {
        List<Notice> noticeList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtils.getConnection();
            String sql = "SELECT * FROM notice ORDER BY createDate DESC";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            
            while (rs.next()) {
                Notice notice = new Notice();
                notice.setId(rs.getInt("id"));
                notice.setTopic(rs.getString("topic"));
                notice.setContent(rs.getString("content"));
                notice.setAuthor(rs.getString("author"));
                notice.setCreateDate(rs.getTimestamp("createDate"));
                noticeList.add(notice);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeAll(conn, ps, rs);
        }
        
        return noticeList;
    }
}